package org.logistics.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.logistics.MainMapActivity;
import org.logistics.MapKeyPermission;
import org.logistics.R;


import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author yimou 
 * 
 */
public class LoginActivity extends Activity {
	
	String TAG = "org.logistics.main";
	String requestUser = null;
	String requestPassWord = null;
	String request = null;
	BufferedReader in = null;
	Context context;
	
	EditText etPwd;
	EditText etUser;
	TextView textUser;
	TextView textPwd;
	TextView loginSuccess;
	Button bn;
	RatingBar rb;
	
	//进度条
	 public float  num=1;
	 
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		/**
		 * 判断网络状态
		 */
		MapKeyPermission net = new MapKeyPermission();
		boolean isNet = net.checkNetError(getApplicationContext());
		if(isNet == false){
			Toast.makeText(getApplicationContext(), "网络未连接，请先连接网络",
			            		     Toast.LENGTH_SHORT).show();
		}
		
		
		bn =(Button) findViewById(R.id.button1);
		bn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {
					
					/**
					 * 得到输入框数据
					 */
					 etPwd =(EditText) findViewById(R.id.editText1);
					 etUser =(EditText) findViewById(R.id.EditText01);
					 loginSuccess =(TextView) findViewById(R.id.loginSuccess);
					requestUser = etUser.getText().toString().trim();
					requestPassWord = etPwd.getText().toString().trim();
					if(requestUser.equals("") || requestUser == null 
							|| requestPassWord.equals("") || requestPassWord == null){
						Toast.makeText(getApplicationContext(), "账号或密码为空 ，请正确输入",
		            		     Toast.LENGTH_SHORT).show();
					}
					
					/**
					 * 向服务器发送请求
					 */
					request = "http://sj.jy100.com//Login.ashx?userName="+
												requestUser+"&password="+requestPassWord;
					HttpClient hc = new DefaultHttpClient();
					HttpPost hp = new HttpPost(request);
					
					/**
					 * 得到服务器结果
					 */
					HttpResponse response = hc.execute(hp);  
			            in = new BufferedReader(  
			                    new InputStreamReader(  
			                            response.getEntity().getContent()));  
			 
			            StringBuffer string = new StringBuffer("");  
			            String lineStr = "";  
			            while ((lineStr = in.readLine()) != null) {  
			                string.append(lineStr + "\n");  
			            }  
			            in.close();  
			            String resultStr = string.toString();  
			            Log.i(TAG, resultStr);
			            
			           
			            JSONObject jo = new JSONObject(resultStr);
			            String lastResult = jo.getString("LoginResult");
			            
			            Log.i(TAG, lastResult);
			            
			            if(lastResult.equals("-1")){
			            	Toast.makeText(getApplicationContext(), "账号或密码错误，请重新输入！",
			            		     Toast.LENGTH_SHORT).show();
			            }else if(lastResult.equals("0")){
			            		//隐藏控件
			            		etPwd.setVisibility(View.GONE);
			            		etUser.setVisibility(View.GONE);
			            		textUser = (TextView)findViewById(R.id.TextView01);
			            		textPwd = (TextView)findViewById(R.id.textView1);
			            		textUser.setVisibility(View.GONE);
			            		textPwd.setVisibility(View.GONE);
			            		bn.setVisibility(View.GONE);
			            		//显示控件
			            		loginSuccess.setVisibility(View.VISIBLE);
			            		 rb=(RatingBar)findViewById(R.id.ratingBar1);
			    				 rb.setVisibility(View.VISIBLE);
			    				//进度条
			    				 Asyn asyn = new Asyn();
			    				 asyn.execute();
			    				 String result = asyn.doInBackground();
			    				 if(result.equals("timeOver") || result == "timeOver"){
			    					 Toast.makeText(getApplicationContext(), "登陆成功",
			            		     Toast.LENGTH_SHORT).show();
			            			//Thread.sleep(1000); 
			            			openMainMapnActivity(v);
			            			finish();
			    				 }
			            }else{
			            	Toast.makeText(getApplicationContext(), "系统错误",
			            		     Toast.LENGTH_SHORT).show();
			            }
			            
			            
			            
				} catch (Exception e) {
					
					System.out.println( "e="+e.getMessage());
				
				}finally {  
		            if (in != null) {  
		                try {  
		                    in.close();  
		                } catch (IOException e) {  
		                    e.printStackTrace();  
		                }  
		            }  
		        }  
				
				
			}
		});
		
		
	}

	/**
	 * 跳转页面
	 * @param v
	 */
	 public void openMainMapnActivity(View v)
	    {
	    	Intent intent = new Intent();
	    	intent.setClass(LoginActivity.this, LoginMainActivity.class);
	    	intent.putExtra("userAccount", requestUser);
	    	intent.putExtra("centerNum", -1);
	    	startActivity(intent);
	    }
	 
	
	   /**
	    * 
	    */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	/**
	 * 
	 */
	  class Asyn extends AsyncTask<String, String, String> {
			protected String doInBackground(String... params) {
					
			        for (int i = 0; i <6; i++) {
			        	rb.setRating(num);
			        	System.out.print("num");
			        	num++;
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					return "timeOver";
			}

			@Override
			protected void onPostExecute(String result) {
			}

			@Override
			protected void onPreExecute() {
			}

		}
	
	
}
